package ben 
{
	import com.greensock.TweenMax;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.text.TextField;
	/**
	 * ...
	 * @author Ben.
	 */
	public class ImgTools extends EventDispatcher
	{
		private var ml:Loader
		private var ww:int
		private var hh:int
		private var cc:Sprite
		private var ii:String
		
		private var ha:String
		
		public function ImgTools() 
		{
			// NEW IMG TOOLS
		}
		
		public function ImgFitSize(_i:String, _c:Sprite, _w:Number, _h:Number, _ha:String = "center"):void
		{
			ww = _w;
			hh = _h;
			cc = _c;
			ha = _ha;
			ii = _i;
			
			ml = new Loader();
			ml.contentLoaderInfo.addEventListener(Event.INIT, onMediaReady);
			ml.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onMediaError);
			var lc:LoaderContext = new LoaderContext(true);
			
			ml.load(new URLRequest(_i), lc);
		}
		
		private function onMediaReady(e:Event):void 
		{
			ml.contentLoaderInfo.removeEventListener(Event.INIT, onMediaReady);
			ml.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onMediaError);
			
			var bd:BitmapData = new BitmapData(ml.width, ml.height);
			bd.draw(ml, null, null, null, null, true);
			var bmp:Bitmap = new Bitmap(bd, "auto", true);
			bd = null;
			
			// RESIZE BMP
			var ri:Number = bmp.width / bmp.height;
			var rc:Number = ww / hh;
			
			if (rc <= ri)
			{
				bmp.width = ww;
				bmp.height = bmp.width / ri;
			}
			if (rc > ri)
			{
				bmp.height = hh;
				bmp.width = bmp.height * ri;
			}
			
			switch(ha)
			{
				case "left":
					bmp.x = 0;
					break;
				case "right":
					bmp.x = - bmp.width;
					break;
				case "center":
					bmp.x = - bmp.width / 2;
					break;
				default:
					bmp.x = - bmp.width / 2;
					break;
			}
			
			bmp.y = - bmp.height / 2;
			
			bmp.alpha = 0;
			
			TweenMax.to(bmp, 0.7, {alpha:1 } );
			
			cc.addChild(bmp);
			
			var tt:TextField = new TextField();
			tt.y = 0;
			tt.width = 100;
			tt.x = -50;
			tt.text = ii;
			cc.addChild(tt);
			
			dispatchEvent(new Event("LOADED"));
		}
		
		private function onMediaError(e:IOErrorEvent):void 
		{
			dispatchEvent(new Event("ERROR_IMG"));
		} 
		
	}

}